/**
 * OpenID 管理工具
 * 用于统一管理微信和支付宝的用户标识
 */

import { useMainStore } from '@/store/store';

/**
 * 获取当前的 openid
 * @returns {string} 当前的 openid
 */
export function getCurrentOpenid() {
    const main = useMainStore();
    return main.GET_OPENID();
}

/**
 * 设置 openid
 * @param {string} openid 要设置的 openid
 */
export function setCurrentOpenid(openid) {
    const main = useMainStore();
    main.SET_OPENID(openid);
}

/**
 * 清除 openid
 */
export function clearCurrentOpenid() {
    const main = useMainStore();
    main.CLEAR_OPENID();
}

/**
 * 从微信授权结果中提取并保存 openid
 * @param {object} authResult 微信授权结果
 */
export function saveWechatOpenid(authResult) {
    if (authResult && authResult.openId) {
        console.log('保存微信 openId:', authResult.openId);
        setCurrentOpenid(authResult.openId);
        return authResult.openId;
    }
    return null;
}

/**
 * 从支付宝授权结果中提取并保存 buyerId 作为 openid
 * @param {object} authResult 支付宝授权结果
 */
export function saveAlipayOpenid(authResult) {
    if (authResult && authResult.buyerId) {
        console.log('保存支付宝 buyerId 作为 openId:', authResult.buyerId);
        setCurrentOpenid(authResult.buyerId);

        // 同时保存到 buyer_id 存储（兼容现有逻辑）
        uni.setStorageSync('buyer_id', authResult.buyerId);

        return authResult.buyerId;
    }
    return null;
}

/**
 * 检查当前是否有有效的 openid
 * @returns {boolean} 是否有有效的 openid
 */
export function hasValidOpenid() {
    const openid = getCurrentOpenid();
    return !!(openid && openid.length > 0);
}

/**
 * 获取用于登录接口的 openid 参数
 * 如果没有 openid，返回空字符串而不是 null
 * @returns {string} 用于登录接口的 openid
 */
export function getLoginOpenid() {
    const openid = getCurrentOpenid();
    return openid || '';
}

/**
 * 调试信息：打印当前 openid 状态
 */
export function debugOpenidInfo() {
    const openid = getCurrentOpenid();
    const buyerId = uni.getStorageSync('buyer_id');
    const storedOpenid = uni.getStorageSync('openid');

    console.log('=== OpenID 状态调试信息 ===');
    console.log('当前 openid (store):', openid);
    console.log('buyer_id (storage):', buyerId);
    console.log('openid (storage):', storedOpenid);
    console.log('是否有效:', hasValidOpenid());
    console.log('=========================');

    return {
        currentOpenid: openid,
        buyerId: buyerId,
        storedOpenid: storedOpenid,
        isValid: hasValidOpenid()
    };
} 